# coding:utf-8

import json
from wsgiref.simple_server import make_server
from change import Change
from detect import Detect
from extract import Extract
from classify import Classify
import re
import cv2
import base64
import numpy as np


def image_to_base64(image_np):
    """
    将np图片(imread后的图片）转码为base64格式
    image_np: 图像，numpy.ndarray
    Returns: base64编码后数据
    """
    image = cv2.imencode('.png', image_np)[1]
    image_code = str(base64.b64encode(image))[2:-1]
    return image_code


def base64_to_image(base64_code):
    """
    将base64编码解析成opencv可用图片
    base64_code: base64编码后数据
    Returns: cv2图像，numpy.ndarray
    """
    # base64解码
    img_data = base64.b64decode(base64_code)
    # 转换为np数组
    img_array = np.fromstring(img_data, np.uint8)
    # 转换成opencv可用格式
    img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)

    return img
# 定义函数，参数是函数的两个参数，都是python本身定义的，默认就行了。


def application(environ, start_response):
    # 定义文件请求的类型和当前请求成功的code
    start_response('200 OK', [('Content-Type', 'text/plain')])
    # environ是当前请求的所有数据，包括Header和URL，body

    request_body = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))

    json_str = request_body.decode('utf-8')  # byte 转 str

    json_str = re.sub('\'', '\"', json_str)  # 单引号转双引号, json.loads 必须使用双引号
    json_dict = json.loads(json_str)  # （注意：key值必须双引号）
    type = json_dict['type']
    if type == 0:       # 第一种功能：变换检测
        img1 = base64_to_image(json_dict['image1'].split(',')[-1])
        img2 = base64_to_image(json_dict['image2'].split(',')[-1])
        pred = model1.forward(img1, img2)
    elif type == 1:     # 第二种功能：目标检测
        img1 = base64_to_image(json_dict['image1'].split(',')[-1])
        pred = model2.forward(img1)
    elif type == 2:     # 第三种功能：目标提取
        img1 = base64_to_image(json_dict['image1'].split(',')[-1])
        pred = model3.forward(img1)
    elif type == 3:     # 第四种功能：地物分类
        img1 = base64_to_image(json_dict['image1'].split(',')[-1])
        pred = model4.forward(img1)
    else:
        pred = None
    pred = image_to_base64(pred)
    result = {'pred': pred}   #pred为每个功能输出的结果，要先转换为base64
    return [json.dumps(result).encode('utf-8')]


if __name__ == "__main__":
    global model1, model2, model3, model4
    model1 = Change()
    model2 = Detect()
    model3 = Extract()
    model4 = Classify()
    port = 6088
    httpd = make_server("0.0.0.0", port, application)
    print("serving http on port {0}...".format(str(port)))
    httpd.serve_forever()
